<template>
  <div style="display: flex;">
    <el-menu
        active-text-color="#ffd04b"
        background-color="#313132"
        class="el-menu-vertical-demo"
        default-active="2"
        text-color="#fff"
        @open="handleOpen">
      <el-sub-menu index="1">
        <template #title>
          <el-icon><DataLine /></el-icon>
          <span>sixseven</span>
        </template>
        <el-menu-item-group title="管理">
          <el-menu-item @click="toTarget(0)" index="1-1">商品列表</el-menu-item>
          <el-menu-item @click="toTarget(1)" index="1-2">订单列表</el-menu-item>
          <el-menu-item @click="toTarget(2)" index="1-3">用户列表</el-menu-item>
          <el-menu-item @click="toTarget(3)" index="1-4">公告列表</el-menu-item>
        </el-menu-item-group>
      </el-sub-menu>
      <el-sub-menu index="2">
        <template #title>
          <el-icon>
            <location/>
          </el-icon>
          <span>Navigator One</span>
        </template>
        <el-menu-item-group title="Group Two">
          <el-menu-item index="2-1">item one</el-menu-item>
          <el-menu-item index="2-2">item two</el-menu-item>
        </el-menu-item-group>
      </el-sub-menu>
      <el-sub-menu index="3">
        <template #title>
          <el-icon><Setting /></el-icon>
          <span>Navigator One</span>
        </template>
        <el-menu-item-group title="Group Tree">
          <el-menu-item index="3-1">item one</el-menu-item>
          <el-menu-item index="3-2">item two</el-menu-item>
        </el-menu-item-group>
      </el-sub-menu>
    </el-menu>
    <div>
      <template v-if="target === 0">
        <div style="width: 100%">
          <div style="margin: 10px 0 10px 0">
            <el-button type="primary" @click="add">新增</el-button>
            <el-button>其它</el-button>
          </div>
          <div style="margin: 10px 0 10px 0">
            <el-input v-model="search" placeholder=" 请 输 入 关 键 字 " style="width:30%"></el-input>
            <el-button style="margin-left: 10px" type="primary" @click="list">查询</el-button>
          </div>
          <el-table :data="tableData" stripe style="width: 1300px;">
            <!--<el-table-column prop="imgPath" label="图片"></el-table-column>-->
            <!--<el-table-column sortable prop="date" label="日期"></el-table-column>-->
            <el-table-column align="center" label="图片" width="180">
              <template #default="scope">
                <div style="display: flex; align-items: center;">
                  <!--<el-image :preview-src-list="srcList" />-->
                  <el-image preview-teleported="true" :src="'/src/' + scope.row.imgPath"/>
                  <!--<el-image preview-teleported="true" :src="'/src/' + scope.row.imgPath" :preview-src-list="srcList" />-->
                  <!--<el-image preview-teleported="imgPath" />-->
                </div>
              </template>
            </el-table-column>
            <el-table-column align="center" sortable prop="id" label="ID"></el-table-column>
            <el-table-column align="center" prop="name" label="商品名"></el-table-column>
            <el-table-column align="center" prop="price" label="价格"></el-table-column>
            <el-table-column align="center" prop="stock" label="库存"></el-table-column>
            <el-table-column align="center" prop="sales" label="销量"></el-table-column>
            <el-table-column align="center" prop="status" label="位置" :formatter="cowryStatus"></el-table-column>
            <el-table-column align="center" fixed="right" label="操作" width="180">
              <template #default="scope">
                <el-button @click="handleEdit(scope.row)" type="primary">编辑</el-button>
                <!--<el-button @click="del(scope.row.id)" type="text">删除</el-button>-->
                <el-popconfirm title="你确定要删除该数据吗？" @confirm="del(scope.row.id)">
                  <template #reference>
                    <el-button type="danger">删除</el-button>
                  </template>
                </el-popconfirm>
              </template>
            </el-table-column>
          </el-table>
          <div style="padding-left: 25%;padding-top: 10px;tab-size: 16px">
            <el-pagination
                small
                background
                layout="prev, pager, next, sizes, total, jumper"
                class="mt-4"
                @size-change="pageSizeChange"
                @current-change="currentChange"
                :total="total"
                :current-page="currentPage"
                :page-sizes="[5,10]"
                :page-size="pageSize"
            />
          </div>
        </div>
        <div>
          <el-dialog title="提示：1：首页展品，2：首页商品，3：折扣一区，4：折扣二区，5：电脑专区，6：配件专区"
                     v-model="dialogVisible" :before-close="handleClose" width="30%">
            <el-form enctype="multipart/form-data" :model="form" :rules="rules" ref="form" label-width="120px">
              <el-form-item label="图片" v-model="form.imgPath" prop="imgPath">
                  <el-upload
                      name="img"
                      list-type="picture-card"
                      class="avatar-uploader"
                      action="/api/upload"
                      :show-file-list="false"
                      :on-success="handleAvatarSuccess"
                      :before-upload="beforeAvatarUpload"
                  >
                    <el-icon v-if="!dialogImageUrl"><Plus/></el-icon>
                    <img v-if="dialogImageUrl!=''" :src="'/src/' + dialogImageUrl" class="avatar" style="width: 148px; height: 148px">
                  </el-upload>
              </el-form-item>
              <el-form-item label="商品名" prop="name">
                <el-input v-model="form.name" style="width: 80%"></el-input>
              </el-form-item>
              <el-form-item label="价格" prop="price">
                <el-input v-model="form.price" style="width: 80%"></el-input>
              </el-form-item>
              <el-form-item label="销量" prop="sales">
                <el-input v-model="form.sales" style="width: 80%"></el-input>
              </el-form-item>
              <el-form-item label="库存" prop="stock">
                <el-input v-model="form.stock" style="width: 80%"></el-input>
              </el-form-item>
              <el-form-item label="位置" prop="stock">
                <el-input v-model="form.status" style="width: 80%"></el-input>
              </el-form-item>
            </el-form>
            <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false; deleteLastImg('')">取 消</el-button>
          <el-button type="primary" @click="save">确 定</el-button>
        </span>
            </template>
          </el-dialog>
        </div>
      </template>
      <template v-if="target === 1"><order/></template>
      <template v-if="target === 2"><member/></template>
      <template v-if="target === 3"><announcement/></template>
    </div>

  </div>
</template>

<script>
import request from "@/utils/request.js";
import { Delete, Download, Plus, ZoomIn } from '@element-plus/icons-vue'
import {ElMessage, ElMessageBox} from "element-plus";
import Order from "@/views/admin/order.vue";
import Member from "@/views/admin/member.vue";
import Announcement from "@/views/admin/announcement.vue";
export default {
  name: "admin",
  components: {Announcement, Member, Order},
  data() {
    return {
      pageSize: 5,
      currentPage: 1,
      total: 5,
      form: {},
      dialogImageUrl: '',
      dialogVisible: false,
      disabled: false,
      search: '',
      target: 0,
      tableData: [
        {
          id: "2023",
          name: "坤坤",
          maker: "xxx",
          price: 11,
          stock: 123,
          imgPath: "xxx",
          sales: "巴拉巴拉巴拉巴拉"
        }
      ],
      hireType: [
        {
          id: 1,
          value: '首页展品'
        },
        {
          id: 2,
          value: '首页商品'
        },
        {
          id: 3,
          value: '折扣一区'
        },
        {
          id: 4,
          value: '折扣二区'
        },
        {
          id: 5,
          value: '电脑专区'
        },
        {
          id: 6,
          value: '配件专区'
        },
      ],
    }
  },
  created() {
    this.list();
  },
  methods: {
    cowryStatus(row, column, cellValue){
      const obj = this.hireType.find(item => item.id === cellValue);
      return obj ? obj.value : '你猜';
    },
    currentChange(pageNum) {
      this.currentPage = pageNum;
      this.list();
    },
    pageSizeChange(pageSize) {
      this.pageSize = pageSize;
      this.list();
    },
    toTarget(num) {
      this.target = num;
      // console.log("num=", num);
    },
    list() {
      // console.log("currentPage=", this.currentPage);
      // console.log("pageSize=", this.pageSize);
      request.get("/api/listPageByConditionName", {
        params: {
          pageNum: this.currentPage,
          pageSize: this.pageSize,
          searchName: this.search
        }
      }).then(
          res => {
            console.log("res=", res);
            if (res.code === '200') {
              this.tableData = res.data.records;
              // for (const record of res.data.records) {
              //   this.srcList.push({imgPath: '/src/' +record.imgPath});
              // }
              // console.log("srcList=",this.srcList)
              this.total = res.data.total;
            }
          }
      )
    },
    add() {
      sessionStorage.removeItem("dialogImageUrl");
      this.dialogVisible = true;
      this.dialogImageUrl = '';
      this.form = {};
    },
    handleClose(){
      ElMessageBox.confirm('你确定要退出')
          .then(() => {
            this.deleteLastImg('');
            this.dialogVisible = false;
          })
          .catch(() => {
            // catch error
          })
    },
    deleteLastImg(msg){
      //删除替换前的照片
      if (sessionStorage.getItem("dialogImageUrl")){
        request.get("/api/deleteLastImg",{
          params: {
            lastImageUrl: sessionStorage.getItem("dialogImageUrl")
          }
        }).then(
            res => {
              if (res.code === "200"){
                if (msg){
                  ElMessage({
                    message: msg,
                    type: 'success',
                  })
                }
              }else {
                ElMessage({
                  message: '图片更改失败',
                  type: 'error',
                })
              }
            }
        )
      }
    },
    handleAvatarSuccess(res, file){
      console.log("res=", res);
      if (res.code === '200'){
        this.deleteLastImg('图片更换成功');
        sessionStorage.setItem("dialogImageUrl", res.data);
        this.dialogImageUrl = res.data;
        ElMessage({
          message: '图片加载成功',
          type: 'success',
        })
      }
      if (res.code === '555'){
        ElMessage({
          message: '上传的图片上传图片失败',
          type: 'error',
        })
      }
    },
    beforeAvatarUpload(file){
      const isLimitFile = file.size / 1024 / 1024 < 2;
      if (!isLimitFile){
        ElMessage({
          message: '上传的图片不能超过2MB',
          type: 'error',
        })
      }
    },
    // imgList(){
    //   let list = this.srcList;
    // },
    handleEdit(row) {
      this.form = JSON.parse(JSON.stringify(row));
      sessionStorage.setItem("dialogImageUrl", row.imgPath);
      this.dialogImageUrl = row.imgPath;
      this.dialogVisible = true;
      // this.$refs['form'].resetFields();//将上传验证消息清空
    },
    save(){
      if (this.form.id){
        this.form.imgPath = this.dialogImageUrl;
        request.put("/api/modifyCowry", this.form).then(
            res => {
              if (res.code === "200"){
                ElMessage({
                  message: '修改成功',
                  type: 'success',
                })
                sessionStorage.removeItem("dialogImageUrl");
              }else {
                ElMessage({
                  message: '修改失败',
                  type: 'error',
                })
              }
              this.list();
              this.dialogVisible = false;
            }
        )
      }else {
        this.form.imgPath = this.dialogImageUrl;
        request.post("/api/addCowry", this.form).then(
            res => {
              console.log("res=", res);
              if (res.code === '200'){
                ElMessage({
                  message: '提交成功',
                  type: 'success',
                })
                this.dialogVisible = false;
                this.dialogImageUrl = '';
                sessionStorage.removeItem("dialogImageUrl");
                this.list();
              }
              if (res.code === '555'){
                ElMessage({
                  message: '提交失败',
                  type: 'error',
                })
              }
            }
        )
      }

    },
    del(id){
      // console.log("id=", id)
      request.delete("/api/deleteCowry/" + id).then(
          res => {
            if (res.code === '200'){
              ElMessage({
                message: '删除成功',
                type: 'success',
              })
            }
            if (res.code === '555'){
              ElMessage({
                message: '删除失败',
                type: 'error',
              })
            }
            this.list();
          }
      )
    },
  }
}
</script>

<style scoped>

</style>